package fe.pong.tennis.input;

import flash.display.DisplayObject;
import flash.display.Stage;
import flash.events.TouchEvent;
import flash.geom.Point;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;

class InputManagerTouch implements InputManager {

	private static var _MOVIMIENTO_MINIMO: Float = 20;

	private var _origen: Point;
	private var _movimiento: Point;

	public function new (sprite: DisplayObject) {
		if (Multitouch.supportsTouchEvents) {
			sprite.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchBegin);
			sprite.addEventListener(TouchEvent.TOUCH_MOVE, onTouchMove);
			sprite.addEventListener(TouchEvent.TOUCH_END, onTouchEnd);
		}
		_origen = new Point(0, 0);
		_movimiento = new Point(0, 0);
	}

     private function onTouchBegin(e:TouchEvent):Void {
    	setVector(_origen, e.stageX, e.stageY);
	}

     private function onTouchMove(e:TouchEvent):Void {
		var movX: Float = e.stageX - _origen.x;
		var movY: Float = e.stageY - _origen.y;
		if (Math.abs(movX) < _MOVIMIENTO_MINIMO && Math.abs(movY) < _MOVIMIENTO_MINIMO) {
			setVector(_movimiento, 0, 0);
		} else {
			setVector(_movimiento, movX, movY);
		}
    }

     private function onTouchEnd(e:TouchEvent):Void {
		setVector(_origen, 0, 0);
		setVector(_movimiento, 0, 0);
    }

	private static function setVector(vector: Point, x: Float, y: Float) {
		vector.x = x;
		vector.y = y;
	}

	public function getPosicion(): Point {
		return _origen;
	}

	public function getGesto(): Point {
		return _movimiento;
	}

	public function isPressing(): Bool {
		return (_origen.x != 0 || _origen.y != 0);
	}

	public function isMoving(): Bool {
		return (_movimiento.x != 0 || _movimiento.y != 0);
	}

}
